<?php

class BaiduUtil {

    /**
     * 上传图片到百家号
     * @param string $picPath
     * @param string $cookie
     */
    public static function upload($picPath, $cookie) {
        $post_data['media'] = new CURLFile($picPath);
        $post_data['type'] = 'image';
        $post_data['app_id'] = '1567812318538997';
        $post_data['is_waterlog'] = 1;
        $post_data['save_marerial'] = 1;
        $post_data['no_compress'] = 1;
        $url = "https://baijiahao.baidu.com/builderinner/api/content/file/upload";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
        // 本地测试代理 @TODO 上线需注释掉
//        curl_setopt($ch, CURLOPT_PROXY, '192.168.50.98');
//        curl_setopt($ch, CURLOPT_PROXYPORT, '8888');
        //multipart 方式上传需要注意传递的参数是数组，不是字符串
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        if ($output) {
            $result = json_decode($output, true);
            $res = isset($result['ret']) ? $result['ret'] : [];
            if (!empty($res)) {
                $info = getimagesize($picPath);
                $res['width'] = $info[0] ?: 1178;
                $res['height'] = $info[1] ?: 2160;
            }
            return $res;
        } else {
            return [];
        }
    }

    /**
     * 根据图片链接上传百家号图床
     * @param string $picUrl
     * @param string $cookie
     * @return string
     */
    public static function uploadByUrl($picUrl, $cookie) {
        $path = '/usr/share/nginx/html/cron/res/images/nav/';
        if (ENVIRONMENT == 'development') {
            $path = APPPATH . '../res/images/nav/';
        }

        $filePath = $path . uniqid();
        if (!file_exists($path)) {
            mkdir($path);
            chmod($path, 755);
        }

        $file = @file_get_contents($picUrl);
        if (empty($file)) {
            return [];
        }

        file_put_contents($filePath, $file);
        if (file_exists($filePath)) {
            $res = self::upload($filePath, $cookie);
            @unlink($filePath);
            return $res;
        } else {
            return [];
        }
    }
}
